<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        size="small"
        v-model="listQuery.sort"
        style="width: 300px"
        class="filter-item"
        placeholder="期刊序号或名称"
        clearable
      />
      <el-button
        size="small"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        查询
      </el-button>
      <el-button
        size="small"
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="edit"
        @click="showCreate"
      >
        添加
      </el-button>
    </div>
    <div class="table-container">
      <el-table
        key="tableKey"
        :data="list"
        v-loading="listLoading"
        element-loading-text="加载中"
        border
        fit
        stripe
        highlight-current-row
        style="width: 100%"
      >
        <!-- <el-table-column align="center" label="系统编号"  sortable prop="id" width="120px">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column> -->
        <el-table-column
          align="center"
          label="期刊序号"
          class-name="overflow-on"
          sortable
          prop="sort"
          width="150"
        >
          <template slot-scope="scope">
            {{ scope.row.sort }}
            <el-input
              size="small"
              v-if="scope.row.show == 1"
              max="50"
              v-model="scope.row.sort"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="名称">
          <template slot-scope="scope">
            <span>{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="封面图" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-image
              style=" height:60px"
              :src="scope.row.cover"
              :preview-src-list="scope.row.imglist"
            ></el-image>
            <!-- <img style="width: 60px" :src="scope.row.cover" /> -->
          </template>
        </el-table-column>

        <el-table-column align="center" label="显示状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'warning'">
              <span>{{ scope.row.status == 1 ? "已显示" : "已停用" }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="更新时间"
          sortable
          prop="updated_at"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.updated_at }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="330">
          <template slot-scope="scope">
            <el-button
              plain
              v-if="scope.row.show == 1"
              size="small"
              @click="orderHandleDo(scope.row)"
              >保存</el-button
            >
            <el-button plain v-else size="small" @click="orderHandle(scope.row)"
              >编辑序号</el-button
            >
            <el-button
              plain
              size="small"
              type="primary"
              @click="handleEdit(scope.row, 'edit')"
              >编辑</el-button
            >
            <el-button
              plain
              v-if="scope.row.status == 1"
              size="small"
              type="warning"
              @click="changeStatus(scope.row, 0)"
              >去停用</el-button
            >
            <el-button
              plain
              v-else
              size="small"
              type="success"
              @click="changeStatus(scope.row, 1)"
              >去发布</el-button
            >
            <el-button
              plain
              size="small"
              type="danger"
              @click="handleDel(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container text-right">
      <el-pagination
        background
        :total="pagination.total"
        :current-page="listQuery.page"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form
        class="small-space"
        :model="temp"
        :rules="rules"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="名称" required>
          <el-input
            size="small"
            v-model="temp.title"
            prop="title"
            maxlength="32"
            width="100px"
          ></el-input>
        </el-form-item>

        <el-form-item label="封面图" required>
          <el-upload
            class="avatar-uploader"
            :action="uploadPath"
            :headers="header"
            :show-file-list="false"
            :on-success="handleImageSuccess1"
          >
            <img v-if="temp.cover" :src="temp.cover" style="width: 200px" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <!-- <el-tag type="warning"> 不传则使用该默认图标</el-tag> -->
        </el-form-item>

        <el-form-item label="序号" prop="sort">
          <el-input-number
            size="small"
            v-model="temp.sort"
            style="width:200px;"
            prop="sort"
          />
          <el-tag type="warning">
            备注：默认当前年月，该序号用于排序显示。</el-tag
          >
        </el-form-item>
        <!-- <el-alert :closable="false" title="温馨提示：图片尽量压缩后上传，尽量不超过1M" type="error"></el-alert> -->

        <el-form-item label="内容" prop="content">
          <div style="border: 1px solid #ccc;">
            <Toolbar
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
              style="border-bottom: 1px solid #ccc"
            />
            <Editor
              v-model="temp.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
              style="height: 500px; overflow-y: hidden;"
            />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          type="primary"
          @click="create"
          >确 定</el-button
        >
        <el-button v-else type="primary" @click="update">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { List, Save, Del, Status, Sort } from "@/api/directory";
import { getToken } from "@/utils/auth";
import { uploadPath } from "@/utils/common";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
// 创建一个新的日期对象
var date = new Date();
// 获取当前月份（注意 JavaScript 中月份从0开始计算）
let month = date.getMonth() + 1; // 加上1得到真正的月份值

// 如果月份小于等于9，则需要添加一个零作为前导
if (month <= 9) {
  month = "0" + month;
}
// 通过getFullYear()方法获取当前年份
var currentDate = date.getFullYear() + month;
export default {
  components: { Editor, Toolbar },

  data() {
    return {
      editor: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {}
      },
      mode: "default", // or 'simple'
      btn: false,
      //typeList: [],
      //uploadPath: uploadPath,

      list: null,
      joinArr: null,
      changeIndex: -1,
      pagination: {},
      dialogFormVisible: false,
      temp: {
        title: "",
        cover: "",
        sort: currentDate,
        status: 0,
        content: ""
      },
      listQuery: {
        page: 1,
        limit: 10,
        title: ""
      },

      uploadPath: uploadPath,
      dialogStatus: null,
      dialogTitle: "",
      header: {
        Authorization: getToken()
      },
      rules: {
        title: [{ required: true, message: "请输入标题！", trigger: "blur" }],
        sort: [{ required: true, message: "请输入期刊序号" }]
      }
    };
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  created() {
    this.getList();
    this.editorConfig.MENU_CONF["uploadImage"] = {
      server: uploadPath,
      fieldName: "file",
      // 单个文件的最大体积限制，默认为 2M
      maxFileSize: 2 * 1024 * 1024, // 2M
      // 最多可上传几个文件，默认为 100
      maxNumberOfFiles: 10,
      // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
      allowedFileTypes: ["image/*"],
      // 自定义增加 http  header
      headers: {
        Authorization: getToken()
      },
      // 跨域是否传递 cookie ，默认为 false
      withCredentials: false,
      // 超时时间，默认为 10 秒
      timeout: 5 * 1000, // 5 秒
      // 自定义插入图片
      customInsert(res, insertFn) {
        // res 即服务端的返回结果
        // 从 res 中找到 url alt href ，然后插图图片
        console.log(res.data.filepath);
        insertFn(res.data.filepath, "", "");
      }
    };
  },

  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    getList() {
      this.listLoading = true;
      List(this.listQuery).then(response => {
        var data = response.data;
        this.list = data.data;
        //图片相对路径处理
        //this.list.forEach(item=>{
        //  item.image_path=process.env.VUE_APP_BASE_PIC +  item.image_path

        //})

        this.pagination = data;

        //图片放大处理，声明一个数组，遍历一遍
        this.list.forEach(e => {
          e.imglist = [];
          e.imglist.push(e.cover);
        });
      });

      this.listLoading = false;
    },

    handleFilter() {
      //console.log(this.listQuery)
      this.listQuery.page = 1;
      this.getList();
    },

    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },

    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },

    changeStatus(row, status) {
      Status({ id: row.id, status: status }).then(response => {
        row.status = status;
        this.$message.success("操作成功！");
        this.getList();
      });
    },

    orderHandle(row) {
      row.show = 1;
    },

    orderHandleDo(row) {
      Sort({ id: row.id, sort: row.sort }).then(response => {
        row.show = 0;
        this.getList();
        this.$message.success("操作成功！");
      });
    },

    showCreate() {
      //console.log(currentDate);

      this.temp = {
        title: "",
        content: "",
        cover: "",
        status: 0,
        sort: currentDate
      };
      this.dialogTitle = "添加";
      this.dialogStatus = "create";
      (this.dialogTitle = "添加"), (this.dialogFormVisible = true);
    },

    handleEdit(row, status) {
      this.dialogTitle = "编辑";
      this.dialogFormVisible = true;
      this.temp = JSON.parse(JSON.stringify(row));
      this.dialogStatus = status;
    },

    handleDel(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          Del({ id: row.id }).then(response => {
            if (response.code === 0) {
              this.$message({
                message: response.msg,
                type: "success"
              });
              this.dialogFormVisible = false;
              this.getList();
            } else {
              this.$message({
                message: response.msg,
                type: "error"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    handleImageSuccess1(res, file) {
      if (res.code === 0) {
        this.temp.cover = res.data.filepath;
        this.$forceUpdate();
        //图片相对路径处理
        //this.temp.image_path=process.env.VUE_APP_BASE_PIC +  this.temp.image_path
        // uploadPath = uploadPath.this.temp.image_path;

        this.$message.success("上传成功！");
      } else {
        this.$message.error(res.msg);
      }
    },

    update() {
      Save(this.temp).then(response => {
        if (response.code === 0) {
          this.$message({
            message: response.msg,
            type: "success"
          });
          this.dialogFormVisible = false;
          //this.fetchSetting()
          this.getList();
        } else {
          this.$message({
            message: response.msg,
            type: "error"
          });
        }
      });
    },
    create() {
      Save(this.temp).then(response => {
        if (response.code === 0) {
          this.$message({
            message: response.msg,
            type: "success"
          });
          this.dialogFormVisible = false;
          //this.fetchSetting()
          this.getList();
        }
      });
    }
  }
};
</script>

<style>
/* .table-container {
  margin: 20px 0;
} */
.alert-container {
  margin: 20px 0;
}
</style>
